package com.jy.api.controller.admin;

import com.jy.api.dao.CouponDao;
import com.jy.api.dao.CouponInstanceDao;
import com.jy.api.dao.MemberDao;
import com.jy.api.dao.StoreDao;
import com.jy.api.domain.*;
import com.jy.api.exception.MyException;
import com.jy.api.service.CouponInstanceService;
import com.jy.api.service.WechatService;
import com.jy.api.signUpReq.admin.CouponInstanceSignUpReq;
import com.jy.api.util.ValidatorUtil;
import com.jy.api.vo.admin.coupon.ReceiveCouponInstanceVo;
import com.jy.api.vo.admin.coupon.ShareVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.web.PageableDefault;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/**
 * Created by lihu on 2017/11/23.
 */

@Slf4j
@RestController
@RequestMapping(value = "v1/admin/", produces = "application/json;charset=utf-8")
public class AdminCouponInstanceController {


    @Autowired
    CouponInstanceService couponInstanceService;

    @Autowired
    MemberDao memberDao;

    @Autowired
    CouponInstanceDao couponInstanceDao;

    @Autowired
    CouponDao couponDao;

    @Autowired
    StoreDao storeDao;


    @Autowired
    WechatService wechatService;

    /**
     * 分享地址
     *
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "/coupon-share")
    public ResponseEntity shareUrl(@RequestParam(name = "id") String id) {
        try {
            CouponInstance instance = couponInstanceDao.findOne(id);
            if (instance == null) {
                return new ResponseEntity("优惠卷信息不存在！", HttpStatus.BAD_REQUEST);
            }
            Coupon coupon = couponDao.findOne(instance.getCouponId());
            Store store = storeDao.findOne(instance.getStoreId());
            ShareVo shareVo = new ShareVo(store.getName(), store.getAddr(),
                    coupon.getTitle(), wechatService.getShareUrl(id));

            return new ResponseEntity(shareVo, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("shareUrl  is error==> couponInstanceId{}", id, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * 获取领取优惠卷信息
     *
     * @param couponInstanceId
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "receive/coupon-instance")
    public ResponseEntity receiveCouponInstance(@RequestParam(name = "couponInstanceId") String couponInstanceId) {
        try {

            CouponInstance couponInstance = couponInstanceDao.findOne(couponInstanceId);
            if (couponInstance == null) {
                return new ResponseEntity("优惠卷信息不存在！", HttpStatus.BAD_REQUEST);
            }
            Store store = storeDao.findOne(couponInstance.getStoreId());
            if (store == null) {
                return new ResponseEntity("店铺信息不存在！", HttpStatus.BAD_REQUEST);
            }
            Member member = memberDao.findOne(couponInstance.getOwnerId());
            Coupon coupon = couponDao.findOne(couponInstance.getCouponId());
            ReceiveCouponInstanceVo couponInstanceVo = new ReceiveCouponInstanceVo(member.getOpenId(), member.getMobile(), coupon.getTitle(),
                    store.getName(), coupon.getType());
            return new ResponseEntity(couponInstanceVo, HttpStatus.OK);
        } catch (Exception ex) {
            log.error("getCouponInstance  is error==> couponInstanceId{}", couponInstanceId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * 优惠卷领取
     *
     * @param signUpReq
     * @return
     */
    @Transactional
    @RequestMapping(method = RequestMethod.POST, value = "receive/coupon-instance")
    public ResponseEntity receiveCouponInstance(@Valid @RequestBody CouponInstanceSignUpReq signUpReq,
                                                BindingResult bindingResult) {
        try {
            if (bindingResult.hasErrors()) {
                log.error("【优惠卷领取】参数不正确, signUpReq={}", signUpReq);
                return new ResponseEntity(bindingResult.getFieldError().getDefaultMessage(), HttpStatus.BAD_REQUEST);
            }
            if (!ValidatorUtil.isMobile(signUpReq.getMobile())) {
                return new ResponseEntity("领取失败！电话号码格式有误！", HttpStatus.BAD_REQUEST);
            }

            Member member = memberDao.findOne(signUpReq.getMemberId());
            if (member == null) {
                return new ResponseEntity("领取失败！会员信息不存在！", HttpStatus.BAD_REQUEST);
            }
            CouponInstance couponInstance = couponInstanceDao.findOne(signUpReq.getCouponInstanceId());
            if (couponInstance == null) {
                return new ResponseEntity("领取失败！会员信息不存在！", HttpStatus.BAD_REQUEST);
            }
            if (!StringUtils.equals(member.getId(), couponInstance.getOwnerId())) {
                return new ResponseEntity("领取失败！优惠卷领取人错误！", HttpStatus.BAD_REQUEST);
            }
            if (couponInstance.getStauts() != CouponInstanceStatus.CREATED) {
                return new ResponseEntity("领取失败！优惠卷已领取！", HttpStatus.BAD_REQUEST);
            }
            Coupon coupon = couponDao.findOne(couponInstance.getCouponId());
            member.setMobile(signUpReq.getMobile());
            couponInstance.setStauts(CouponInstanceStatus.NORMAL);
            couponInstance.setBeginTime(coupon.getStartTime());
            couponInstance.setEndTime(coupon.getEndTime());
            memberDao.save(member);
            couponInstanceDao.save(couponInstance);
            return new ResponseEntity(HttpStatus.OK);
        } catch (Exception ex) {
            log.error("getCouponInstance  is error==> signUpReq{}", signUpReq, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }


    /**
     * 获取优惠卷统计信息
     *
     * @param storeId
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(method = RequestMethod.GET, value = "coupon-instance")
    public ResponseEntity getCouponInstance(@RequestParam("storeId") String storeId, @RequestParam("type") String type, @RequestParam(value = "begin", required = false) String begin, @RequestParam(value = "end", required = false) String end, @RequestParam(value = "time", required = false) String time, Pageable pageable) {
        try {
            return ResponseEntity.ok(couponInstanceService.getCouponInstanceTotal(storeId, type, begin, end, time, pageable));
        } catch (Exception ex) {
            log.error("getCouponInstance  is error==> storeId{}", storeId, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }

    }

    /**
     * 获取优惠卷核销信息
     *
     * @param storeId
     * @param pageable
     * @return
     */
    @PreAuthorize("hasRole('ADMIN')")
    @RequestMapping(method = RequestMethod.GET, value = "coupon-instance/list")
    public ResponseEntity getCouponInstanceList(@RequestParam(value = "storeId") String storeId,
                                                @PageableDefault(value = 10, sort = {"validateTime"}, direction = Sort.Direction.DESC) Pageable pageable) {
        return new ResponseEntity(couponInstanceService.getvalidate(storeId, pageable), HttpStatus.OK);
    }


    /**
     * 获取优惠卷详情
     *
     * @param id
     * @param id
     * @return
     */
    @RequestMapping(method = RequestMethod.GET, value = "{id}/coupon-instance")
    public ResponseEntity getCouponInstancedetails(@PathVariable String id) {
        try {

            return ResponseEntity.ok(couponInstanceService.getCouponInstanceDetails(id));
        } catch (MyException ex) {
            log.error("getCouponInstancedetails is error=>id:{}", id, ex);
            return new ResponseEntity(ex.getMessage(), HttpStatus.BAD_REQUEST);
        } catch (Exception ex) {

            log.error("getCouponInstancedetails is error=>id:{}", id, ex);
            return new ResponseEntity("系统运行错误", HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
